//
//  QrCodeViewController.m
//  midea
//
//  Created by 刘 子威 on 15/4/6.
//  Copyright (c) 2015年 Midea. All rights reserved.
//

#import "QrCodeViewController.h"
#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height
#define SCREEN_WIDTH  [UIScreen mainScreen].bounds.size.width

@interface QrCodeViewController ()

@end

@implementation QrCodeViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor grayColor];
    
    //取消按钮
    UIButton * scanButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    scanButton.backgroundColor=[UIColor clearColor];
    [scanButton setTitle:@"关闭窗口" forState:UIControlStateNormal];
    scanButton.frame = CGRectMake((SCREEN_WIDTH - 100)/2, SCREEN_HEIGHT-80, 100 , 40);
    [scanButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:scanButton];
    
    //提示label
    UILabel * labIntroudction= [[UILabel alloc] initWithFrame:CGRectMake(15, 40, 290, 50)];
    labIntroudction.backgroundColor = [UIColor clearColor];
    labIntroudction.numberOfLines = 2;
    labIntroudction.textColor = [UIColor whiteColor];
    labIntroudction.text = @"请把二维码置于扫描框中";
    labIntroudction.textAlignment = 1;
    labIntroudction.lineBreakMode = 0;
    [self.view addSubview:labIntroudction];
    
    [self startAnimation];
}

- (void)startAnimation
{
    //扫瞄框图片
    UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH*3/8/2, SCREEN_HEIGHT/3, SCREEN_WIDTH*5/8, SCREEN_WIDTH*5/8)];
    imageView.image = [UIImage imageNamed:@"app_pick_bg.png"];
    [self.view addSubview:imageView];
    
    upOrdown = NO;
    num =0;
    _line = [[UIImageView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH/4, SCREEN_HEIGHT/3+10, SCREEN_WIDTH/2, 2)];
    _line.image = [UIImage imageNamed:@"app_line.png"];
    [self.view addSubview:_line];
    
    //扫瞄动画定时器
    _timer = [NSTimer scheduledTimerWithTimeInterval:.02 target:self selector:@selector(animation1) userInfo:nil repeats:YES];
}

#pragma mark - 扫描二维码的动画
-(void)animation1
{
    if (upOrdown == NO) {
        num ++;
        _line.frame = CGRectMake(SCREEN_WIDTH/4, SCREEN_HEIGHT/3+10+2*num, SCREEN_WIDTH/2, 2);
        if (2*num == 180) {
            upOrdown = YES;
        }
    }
    else {
        num --;
        _line.frame = CGRectMake(SCREEN_WIDTH/4, SCREEN_HEIGHT/3+10+2*num, SCREEN_WIDTH/2, 2);
        if (num == 0) {
            upOrdown = NO;
        }
    }
    
}

#pragma mark - 取消按钮响应事件
-(void)backAction
{
    __unsafe_unretained typeof(self) this = self;
    
    [self dismissViewControllerAnimated:YES completion:^{
        if(this.timer != nil)
        [this.timer invalidate];
    }];
}

#pragma mark - 视图将要出现
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self setupCamera];
}

#pragma mark - 打开二维码扫描
- (void)setupCamera
{
    // Device
    _device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    // Input
    _input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:nil];
    
    // Output
    _output = [[AVCaptureMetadataOutput alloc]init];
    [_output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    // Session
    _session = [[AVCaptureSession alloc]init];
    [_session setSessionPreset:AVCaptureSessionPresetHigh];
    if ([_session canAddInput:self.input])
    {
        [_session addInput:self.input];
    }
    
    if ([_session canAddOutput:self.output])
    {
        [_session addOutput:self.output];
    }
    
    // 条码类型 AVMetadataObjectTypeQRCode
    if ([self.output.availableMetadataObjectTypes containsObject:AVMetadataObjectTypeQRCode]) {
        _output.metadataObjectTypes = @[AVMetadataObjectTypeQRCode];
        [_output setRectOfInterest : CGRectMake (0.2, 0.3, 0.6, 0.6)];
        // Preview
        _preview =[AVCaptureVideoPreviewLayer layerWithSession:self.session];
        _preview.videoGravity = AVLayerVideoGravityResizeAspectFill;
        _preview.frame =CGRectMake(0,0,SCREEN_WIDTH,SCREEN_HEIGHT);
                [self.view.layer insertSublayer:self.preview atIndex:0];
        
        // Start
        [_session startRunning];
        
    }else{
        NSLog(@"not support AVMetadataObjectTypeQRCode, device maybe a simluator");
        [self backAction];
    }
   }

#pragma mark AVCaptureMetadataOutputObjectsDelegate
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    NSString *stringValue;
    
    if ([metadataObjects count] >0)
    {
        AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex:0];
        stringValue = metadataObject.stringValue;
    }
    
    [_session stopRunning];
    
    __unsafe_unretained typeof(self) this = self;

    [self dismissViewControllerAnimated:YES completion:^{

        if(this.timer != nil)
        {
            [this.timer invalidate];
        }
    }];
    
    self.qrCodeBlock(stringValue);
}

- (void)scanQRCode:(scanSuccessBlock)block
{
    self.qrCodeBlock = block;
}

@end
